%% Author: 77
%% Created: 2011-7-3
%% Description: TODO: Add description to add_node_cmd
-module(add_node_cmd).
-author(kanghua ).  
-email(kanghua151@msn.com).  
-date("2011.07.06").  
%%
%% Include files
%%

%%
%% Exported Functions
%%
-export([handle/3]).

%%
%% API Functions
%%


handle(Content,From,State) ->
	io:format("handle info ~p ~p ~p ~p ~n",[?MODULE,Content,From,State]), %% debug info
	case check_parm(Content) of 
		 true -> 
			 io:format("check parm pass ~n"),
		     {Node} = Content,
			 io:format("node info ~p ~n",[Node]), %% debug info
             case rpc:call(Node,application,start,[node_controller],1000) of
				 {badrpc,{Reason,_}} when Reason /= already_started->
					io:format("start node controller fail ! reason ~p ~n",[Reason]),
                    gen_server:reply(From,{error,nc_start_failed}),
					error;
	    		 _ ->    		
             	 	io:format("start up node controller: ~n"), %% debug info
             		case gen_server:call(meta_server,{fetch_node_resource,{Node}},1000) of
                         {error,Reason} ->
                            io:format("fetch node resource failed ! reason ~p ~n",[Reason]),
                            gen_server:reply(From,{nc_resource_unknown}),
                            error;
						 {ok,Resource} ->
 			 				io:format("node resource back  ~p ~n",[Resource]), %% debug info
             				{HostName,IpAddr,VcpuCount,StorageSize,MemorySize,FreeStorageSize,FreeMemorySize} = Resource,
			 				case meta_data_ops:add_node_resource(HostName,IpAddr,VcpuCount,StorageSize,MemorySize,FreeStorageSize,FreeMemorySize) of
								 ok->
									gen_server:reply(From, ok),
									ok;
								 error->
	         						gen_server:reply(From, {error,internel_error}),
             						error
							end
                    end
			end;
		 false -> 
             gen_server:reply(From,{error,err_param})
    end.
	
%%
%% Local Functions
%%

check_parm(Content)->
	true.
